/**
 * 样式管理器
 */
define( ["config"], function() {
	console.log("cssmanager initialize");
	let config = APP_CONFIG;
	var createLink = function(_url) {
		if(_url) {
			var link = document.createElement("link");
			link.rel = 'stylesheet';
			link.type = 'text/css';
			link.href = config.ROOTPATH + _url;
			return link;
		}
		return false;
	}
	let removeJsonComments = (str) => {
		var uid = '_' + +new Date(), 
        primatives = [], 
        primIndex = 0; 
    return ( 
        str 
        /* Remove strings */
        .replace(/(['"])(\\\1|.)+?\1/g, function(match){ 
            primatives[primIndex] = match; 
            return (uid + '') + primIndex++; 
        }) 
   
        /* Remove Regexes */ 
        .replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){ 
            primatives[primIndex] = $2; 
            return $1 + (uid + '') + primIndex++; 
        }) 
   
        /* 
        - Remove single-line comments that contain would-be multi-line delimiters 
            E.g. // Comment /* <-- 
        - Remove multi-line comments that contain would be single-line delimiters 
            E.g. /* // <-- 
       */ 
        .replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '') 
   
        /* 
        Remove single and multi-line comments, 
        no consideration of inner-contents 
       */ 
        .replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '') 
   
        /* 
        Remove multi-line comments that have a replaced ending (string/regex) 
        Greedy, so no inner strings/regexes will stop it. 
       */ 
        .replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '') 
   
        /* Bring back strings & regexes */ 
        .replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){ 
            return primatives[n]; 
        }) 
    ); 
	}
	let removeJsonSpecialChar = (str) => {
		return str.replace(/\//g, '\/');
	}

	try {
		if(typeof config === 'string') {
			config = JSON.parse(removeJsonSpecialChar(removeJsonComments(config)));
		}
		let csslist = config.cssList;
		var _list = csslist,
			i = 0,
			len, headerDom = document.getElementsByTagName('head')[0];
		if(typeof csslist === 'string') {
			_list = JSON.parse(csslist);
		}
		if(_list.length) {
			len = _list.length;
			for(i = 0; i < len; i++) {
				var link = createLink(_list[i]);
				if(link) {
					headerDom.appendChild(link);
				}
			}
		}
	} catch(e) {
		console.log(e);
	}
});